package com.mj.screenshot.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.SYY.cbsdk.ui.AppControl;
import com.dyk.hfsdk.dao.util.DevListener;
import com.dyk.hfsdk.ui.Access;
import com.mj.screenshot.R;
import com.mj.screenshot.util.DateUtils;
import com.mj.screenshot.util.SDCardUtils;
import com.mj.screenshot.util.SPUtils;
import com.mj.screenshot.widget.DesktopLayout;
import com.mj.screenshot.widget.FloatService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ToggleButton;

/**
 * 截屏
摇一摇和通知栏 暂不成熟并且部分版本不支持 先不显示 TODO

Android悬浮窗口的实现
http://blog.csdn.net/stevenhu_223/article/details/8504058
http://www.cnblogs.com/weixing/p/3414533.html
http://blog.csdn.net/xyz_fly/article/details/7546096
http://easion-zms.iteye.com/blog/1066878
Android中使用代码截图的各种方法总结 
http://blog.csdn.net/woshinia/article/details/11520403
http://gundumw100.iteye.com/blog/899977

Android摇一摇功能 
http://blog.csdn.net/catoop/article/details/8051835
http://blog.csdn.net/jason0539/article/details/10154997
http://blog.csdn.net/xn4545945/article/details/9001097

Android通知栏Notification自定义视图方法
http://blog.csdn.net/cstarbl/article/details/7200757
 * @author zhaominglei
 * @date 2015-2-26
 * 
 */
@SuppressLint("ClickableViewAccessibility")
public class MainActivity extends Activity implements OnClickListener,OnCheckedChangeListener,DevListener {
	@SuppressWarnings("unused")
	private static final String TAG = MainActivity.class.getSimpleName();
	private boolean isExit = false;
	private TimerTask timerTask;
	private LinearLayout miniAdLinearLayout; //迷你广告
	private ToggleButton setting1Switch; //悬浮窗截屏
	private ToggleButton setting2Switch; //摇一摇截屏
	private ToggleButton setting3Switch; //通知栏截屏
	private Button appOffersButton; //推荐应用
	private Access access;
	private AppControl appControl;
	private Intent intent;
	
	//悬浮框
	private WindowManager mWindowManager;
	private WindowManager.LayoutParams mLayoutParams;
	private DesktopLayout mDesktopLayout;
	private long starttime;
	
	//摇一摇
	private SensorManager sensorManager;   
    private Vibrator vibrator;
    private static final int SENSOR_SHAKE = 1; 
    private boolean openSensor = false; // 摇一摇默认关闭
    
    //通知栏
    private int notificationId = 900000;
    private NotificationManager notificationManager;
    private Notification notification;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}
	
	private void init() {
		//悬浮框初始化
		//方法一：直接获取系统窗体创建悬浮框
//		createWindowManager();
//		createDesktopLayout();
		//方法二：通过Service
//		intent = new Intent(getApplicationContext(), FloatService.class);
		
		//摇一摇初始化
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		
		//通知栏初始化
		notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.logo, getResources().getText(R.string.app_name), System.currentTimeMillis());
		notification.contentView = new RemoteViews(getPackageName(), R.layout.notification);
		Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.contentIntent = pendingIntent;
		
		miniAdLinearLayout = (LinearLayout)findViewById(R.id.miniAdLinearLayout);
		setting1Switch = (ToggleButton)findViewById(R.id.screenshot_setting1_switch);
		setting2Switch = (ToggleButton)findViewById(R.id.screenshot_setting2_switch);
		setting3Switch = (ToggleButton)findViewById(R.id.screenshot_setting3_switch);
		appOffersButton = (Button)findViewById(R.id.appOffersButton);

		setting1Switch.setOnCheckedChangeListener(this);
		setting2Switch.setOnCheckedChangeListener(this);
		setting3Switch.setOnCheckedChangeListener(this);
		appOffersButton.setOnClickListener(this);
		
		Boolean setting1 = (Boolean)SPUtils.get(this, "screenshot_setting1_switch", false);
		if (setting1) {
			setting1Switch.setChecked(true);
		}
		Boolean setting2 = (Boolean)SPUtils.get(this, "screenshot_setting2_switch", false);
		if (setting2) {
			setting2Switch.setChecked(true);
		}
		Boolean setting3 = (Boolean)SPUtils.get(this, "screenshot_setting3_switch", false);
		if (setting3) {
			setting3Switch.setChecked(true);
		}
		
		appControl = AppControl.getInstance();
		appControl.init(MainActivity.this, "4fb26c9c69acb677p9juMmBTRdLkGKoOL6Po9NFcUXsTiG2lgzO4qOdLtX8yVWsJLg", "木蚂蚁");
		appControl.loadPopAd(MainActivity.this);
		appControl.showPopAd(MainActivity.this, 60 * 1000);
		appControl.showInter(MainActivity.this, miniAdLinearLayout);
		
		access = Access.getInstance();
		// 初始化带player_id
		access.init(MainActivity.this, "4fb26c9c69acb677p9juMmBTRdLkGKoOL6Po9NFcUXsTiG2lgzO4qOdLtX8yVWsJLg", "木蚂蚁");
		// 设置初始积分                                                              
		access.setdefaultSCORE(this, 100);
		// 设置获取积分的监听
		access.setAppListener(this, this);
	}

	/**
	 * 创建悬浮窗体
	 */
	@SuppressWarnings("unused")
	private void createDesktopLayout() {
		mDesktopLayout = new DesktopLayout(this);
		mDesktopLayout.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent event) {
				onActionMove(view, event);
				return true;
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (sensorManager != null) {
			sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (sensorManager != null) {
			sensorManager.unregisterListener(sensorEventListener);
		}
	}

	/**
	 * 设置WindowManager
	 */
	@SuppressWarnings({ "unused"})
	private void createWindowManager() {
		// 取得系统窗体
		mWindowManager = (WindowManager) getApplicationContext()
				.getSystemService(WINDOW_SERVICE);

		// 窗体的布局样式
		mLayoutParams = new WindowManager.LayoutParams();

		// 设置窗体显示类型——TYPE_SYSTEM_ALERT(系统提示)
		mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;

		// 设置窗体焦点及触摸：
		// FLAG_NOT_FOCUSABLE(不能获得按键输入焦点)
		mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

		// 设置显示的模式
		mLayoutParams.format = PixelFormat.RGBA_8888;

		// 设置对齐的方法
		mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;

		// 设置窗体宽度和高度
		mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

		// 设置窗体显示的位置，否则在屏幕中心显示
		mLayoutParams.x = 50;
		mLayoutParams.y = 50;
	}

	private void onActionMove(View view, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			long end = System.currentTimeMillis() - starttime;
			// 双击的间隔在 200ms 到 500ms 之间
			if (end > 200 && end < 500) {
				closeDesk();
				return;
			}
			starttime = System.currentTimeMillis();
		}

		mLayoutParams.x = (int) (event.getRawX() - (mDesktopLayout.getWidth()));
		mLayoutParams.y = (int) (event.getRawY() - (mDesktopLayout.getHeight()));

		mWindowManager.updateViewLayout(mDesktopLayout, mLayoutParams);
		screenshot1();
//		screenshot2(view);
	}

	/**
	 *  需要root权限
	 */
	private void screenshot1() {
		String filepath = SDCardUtils.getSavePath() +"screenshot_"+DateUtils.format(new Date(), "yyyyMMddHHmmss")+".png";
		String cmd = "su -c screencap -p "+filepath;
		try {
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}
		File file = new File(filepath);
		if (file.exists()) {
			Toast.makeText(getApplicationContext(), "保存到："+filepath, Toast.LENGTH_SHORT).show();
		}
	}
	/**
	 *  v.getRootView()截取当前应用窗口 当悬浮窗口调用时只能截取悬浮窗口
	 */
	private void screenshot2(View v) {
		View view = v.getRootView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		if (bitmap != null) {
			try {
				String filepath = SDCardUtils.getSavePath()+"screenshot_"+DateUtils.format(new Date(), "yyyyMMddHHmmss")+".png";
				FileOutputStream out = new FileOutputStream(filepath);
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 显示DesktopLayout
	 */
	@SuppressWarnings("unused")
	private void showDesk() {
		mWindowManager.addView(mDesktopLayout, mLayoutParams);
	}

	/**
	 * 关闭DesktopLayout
	 */
	private void closeDesk() {
		mWindowManager.removeView(mDesktopLayout);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.appOffersButton:
			screenshot2(view);
			access.openWALL(MainActivity.this);
			break;

		default:
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		appControl.close(this);
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.screenshot_setting1_switch:
			intent = new Intent(getApplicationContext(), FloatService.class);
			if (isChecked) {
//				showDesk();
				startService(intent);
				
				SPUtils.remove(getApplicationContext(), "screenshot_setting1_switch");
				SPUtils.put(getApplicationContext(), "screenshot_setting1_switch", true);
			} else {
//				closeDesk();
				stopService(intent);
				
				SPUtils.remove(getApplicationContext(), "screenshot_setting1_switch");
			}
			break;
		case R.id.screenshot_setting2_switch:
			if (isChecked) {
				openSensor = true;
				SPUtils.remove(getApplicationContext(), "screenshot_setting2_switch");
				SPUtils.put(getApplicationContext(), "screenshot_setting2_switch", true);
			} else {
				openSensor = false;
				SPUtils.remove(getApplicationContext(), "screenshot_setting2_switch");
			}
			break;
		case R.id.screenshot_setting3_switch:
			if (isChecked) {
				notificationManager.notify(notificationId, notification);
				SPUtils.remove(getApplicationContext(), "screenshot_setting3_switch");
				SPUtils.put(getApplicationContext(), "screenshot_setting3_switch", true);
			} else {
				notificationManager.cancel(notificationId);
				SPUtils.remove(getApplicationContext(), "screenshot_setting3_switch");
			}
			break;
		default:
			break;
		}
	}
	
	
    /** 
     * 重力感应监听 
     */   
	private SensorEventListener sensorEventListener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {
			// 传感器信息改变时执行该方法
			float[] values = event.values;
			float x = values[0]; // x轴方向的重力加速度，向右为正
			float y = values[1]; // y轴方向的重力加速度，向前为正
			float z = values[2]; // z轴方向的重力加速度，向上为正
//			Log.i(TAG, "x轴方向的重力加速度" + x + "；y轴方向的重力加速度" + y + "；z轴方向的重力加速度" + z);
			// 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
			int medumValue = 19;// 如果不敏感请自行调低该数值,低于10的话就不行了,因为z轴上的加速度本身就已经达到10了
			if (Math.abs(x) > medumValue || Math.abs(y) > medumValue
					|| Math.abs(z) > medumValue) {
				if (openSensor) {
					vibrator.vibrate(200);
					Message msg = new Message();
					msg.what = SENSOR_SHAKE;
					handler.sendMessage(msg);
				}
			}
		}
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};
	
    /** 
     * 动作执行 
     */   
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SENSOR_SHAKE:
				screenshot1();
				break;
			}
		}
	};
	
	@Override
	public void onDevSucceed(int eggs) {
		System.out.println("积分获取成功:" + eggs);
	}

	@Override
	public void onDevFailed(String message) {
		System.out.println("积分获取失败:" + message);
	}

	@Override
	public void onClose(Context context) {
		((Activity) context).finish();
	}
}
